package com.imau.brand.controller;

import com.alibaba.fastjson.JSON;
import com.imau.brand.common.entity.ResultEntity;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 请求处理的基类
 * 拦截请求，获取请求的路径
 */

public class BaseController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         //1.获取请求路径
        String requestURI = request.getRequestURI();
        //2.截取 最后一个/后边路径
        String urlMethod = requestURI.substring(requestURI.lastIndexOf("/")+1);
        //3.反射调用方法
        Class<? extends  BaseController> clazz = this.getClass();
        try {

            //可以是私有的方法
            Method method = clazz.getDeclaredMethod(urlMethod, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);

        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }


    /**前端响应结果JSON格式*/
    public void writeJson(HttpServletResponse response, Object data,boolean success) throws IOException {

        if (success)
        {
            response.getWriter().write(JSON.toJSONString(ResultEntity.SUCCESS(data)));
        }else {

            response.getWriter().write(JSON.toJSONString(ResultEntity.ERROR()));
        }

    }


    public void writeJson(HttpServletResponse response, boolean success) throws IOException {

        if (success)
        {
            response.getWriter().write(JSON.toJSONString(ResultEntity.SUCCESS()));
        }else {

            response.getWriter().write(JSON.toJSONString(ResultEntity.ERROR()));
        }

    }
}
